package com.mindainfo.configCenter.apk.service.impl;

import com.mindainfo.configCenter.apk.bean.ApkInfo;
import com.mindainfo.configCenter.apk.dao.IApkDao;
import com.mindainfo.configCenter.apk.service.IApkService;
import com.mindainfo.configCenter.apk.vo.ApkVo;
import com.mindainfo.configCenter.base.bean.MongoConfig;
import com.mindainfo.configCenter.base.common.DataGrid;
import com.mindainfo.configCenter.base.common.Response;
import com.mindainfo.configCenter.base.common.ResponseFactory;
import com.mindainfo.configCenter.base.dao.impl.MorphiaDao;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.GridFSUploadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.client.gridfs.model.GridFSUploadOptions;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by MD-01 on 2016/11/17.
 */
@Service
public class ApkServiceImpl implements IApkService {

    @Resource
    private IApkDao apkDao;
    @Resource
    private MorphiaDao morphiaDao;

    public DataGrid<ApkVo> queryList(String keyword, Integer page, Integer num) {
        if (page == null) {
            page = 1;
        }
        if (num == null) {
            num = 10;
        }
        int start = (page - 1) * num;
        List<ApkInfo> ApkInfos = apkDao.list(keyword, start, num);

        Function<ApkInfo, ApkVo> function = (info) -> {
                ApkVo vo = new ApkVo();
            vo.setId(info.getId().toString());
            vo.setName(info.getName());
            vo.setArea(info.getArea());
            vo.setCreateTime(
                    FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss")
                            .format(info.getCreateTime()));
            vo.setDownloadCount(info.getDownloadCount());
            vo.setDownloadUrl(info.getDownloadUrl());
            vo.setType(info.getType());
            vo.setVersion(info.getVersion());
            return vo;
        };
        List<ApkVo> vos = ApkInfos.stream()
                .map(function)
                .collect(Collectors.toList());
        int count = apkDao.listCount(keyword);

        DataGrid<ApkVo> dataGrid = new DataGrid<>();
        dataGrid.setCount(count);
        dataGrid.setRows(vos);
        return dataGrid;
    }

    public Response<Void> add(String name, String area,
                              Integer version, String type,
                              MultipartFile file,String preStr){
        if(StringUtils.isEmpty(name)){
            return ResponseFactory.error("name字段不能为空");
        }
        if(StringUtils.isEmpty(area)){
            return ResponseFactory.error("area字段不能为空");
        }
        if(version==null || version <=0){
            return ResponseFactory.error("错误的version");
        }
        if(StringUtils.isEmpty(type)){
            return ResponseFactory.error("type不能为空");
        }
        String id = null;
        try {
            id = morphiaDao.upload(file.getOriginalFilename(),null,file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(StringUtils.isEmpty(id)){
            return ResponseFactory.error("文件上传错误");
        }
        ApkInfo info = new ApkInfo();
        info.setVersion(version);
        info.setDownloadCount(0);
        info.setType(type);
        info.setArea(area);
        info.setName(name);
        info.setCreateTime(new Date());
        info.setDownloadUrl(preStr+"/file/"+id);
        info.setFileId(id);
        apkDao.save(info);
        return ResponseFactory.ok();
    }

    public Response<Void> del(String id){

        ApkInfo info = apkDao.get(id);
        if(info==null){
            return ResponseFactory.error("删除的内容不存在");
        }
        morphiaDao.deleteFile(info.getFileId());
        apkDao.delete(info);
        return ResponseFactory.ok();
    }
}
